﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
//using System.Net.Http;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.Reflection;

namespace myCommon.TCP
{
    public static class http_functions
    {
        public static string getMD5Value(string text)
        {
            byte[] result = Encoding.Default.GetBytes(text);  //tbPass为输入密码的文本框
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToLower(); //tbMd5pass为输出加密文本的文本框
        }
        public static string Login(string url, string content, string username, string password)
        {
            string message = "";
            string password_md5 = getMD5Value(password);

            message += "{";
            message += "\"Command\":";
            message += "\"Login\",";
            message += "\"UserName\":";
            message += "\"" + username + "\",";
            message += "\"Password\":";
            message += "\"" + password_md5 + "\"";
            message += "}";

            return sendHttpPost(url, message, content); ;
            //return sendHttp(cbox_url.Text, message, cbox_content.Text);
        }
        private static void tcp_send(string ip, int port, string message)
        {
            TcpClient tcpClient = new TcpClient();
            //tcpClient.Connect(IPAddress.Parse("170.0.0.78"), 2014);
            tcpClient.Connect(IPAddress.Parse(ip), port);

            NetworkStream ntwStream = tcpClient.GetStream();
            if (ntwStream.CanWrite)
            {
                string str_to_send = Convert.ToChar(2).ToString() + message + Convert.ToChar(3).ToString();
                Byte[] bytSend = Encoding.UTF8.GetBytes(str_to_send);
                //Byte[] bytSend = Encoding.UTF8.GetBytes(message);
                ntwStream.Write(bytSend, 0, bytSend.Length);
            }
            else
            {
                ntwStream.Close();
                tcpClient.Close();
                return;
            }
            ntwStream.Close();
            tcpClient.Close();
        }

        public static string GetIP(bool complete)
        {
            try
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress item in IpEntry.AddressList)
                {
                    //AddressFamily.InterNetwork  ipv4
                    //AddressFamily.InterNetworkV6 ipv6
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (complete == true)
                        {
                            return item.ToString();
                        }
                        else
                        {
                            string[] iparr2 = item.ToString().Split('.');
                            if (iparr2.Length == 4)
                            {
                                return iparr2[0] + "." + iparr2[1] + "." + iparr2[2] + ".";
                            }
                        }
                    }
                }
                return "";
            }
            catch { return ""; }
        }
        public static string sendHttpPost(string url, string str_data, string content_type,string session_id="")
        {
            Encoding myEncoding = Encoding.GetEncoding("gb2312");  //选择编码字符集
            //string data = "sn=" + _uScanCode + "&lanMac=" + _sRecieveLanMac + "&wifiMac=" + _sRecieveWifi2Mac + "&testUserName=" + sTestUser + "&testDateTime=" + sTimeStr;  //要上传到网页系统里的数据（字段名=数值 ，用&符号连接起来）
            byte[] bytesToPost = System.Text.Encoding.Default.GetBytes(str_data); //转换为bytes数据

            string responseResult = String.Empty;
            HttpWebRequest req = (HttpWebRequest)
            HttpWebRequest.Create(url);   //创建一个有效的httprequest请求，地址和端口和指定路径必须要和网页系统工程师确认正确，不然一直通讯不成功
            req.Method = "POST";
            //req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
            //req.ContentType = "application/json;charset=utf8";
            req.ContentType = content_type;
            if (session_id.Length>0) SetHeaderValue(req.Headers, "session_id", session_id);
            req.ContentLength = bytesToPost.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bytesToPost, 0, bytesToPost.Length);     //把要上传网页系统的数据通过post发送
            }
            HttpWebResponse cnblogsRespone = (HttpWebResponse)req.GetResponse();
            if (cnblogsRespone != null && cnblogsRespone.StatusCode == HttpStatusCode.OK)
            {
                StreamReader sr;
                using (sr = new StreamReader(cnblogsRespone.GetResponseStream()))
                {
                    responseResult = sr.ReadToEnd();  //网页系统的json格式的返回值，在responseResult里，具体内容就是网页系统负责工程师跟你协议号的返回值协议内容
                }
                sr.Close();
            }
            cnblogsRespone.Close();
            return responseResult;
        }


        public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }

        }
        public static string sendHttpGet(string url, string str_data, string senssion_id)
        {
            try
            {
                string retString = string.Empty;
                string url_send = url + "?" + str_data;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url_send);
                request.Method = "GET";
                SetHeaderValue(request.Headers, "session_id", senssion_id);



                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(myResponseStream);
                retString = streamReader.ReadToEnd();
                streamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }


    }
}
